import Taro, { Component } from "@tarojs/taro";
import { View, Text } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import { AtForm, AtInput, AtButton, AtRadio } from 'taro-ui'
import { $Req } from "@utils";
import "./createFp.scss"

@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)


export default class Index extends Component {
  config = {
    navigationBarTitleText: "发票申请",
  };

  constructor() {
    this.state = {
      details: {},
      value: '',
      radioVal: '2',
      form: {
        receiptCompany: "",
        receiptTaxpayerNum: "",
        receiptBrandName: "",
        receiptBrandNum: "",
        receiptUserName: "",
        phone: "",
        address: "",
      },
      editFalse: false,
      createTime: ''
    };
  }

  componentDidShow() {
    console.log(JSON.parse(this.$router.params.details));
    this.setState({
      details: JSON.parse(this.$router.params.details),
    }, () => {
        this.getFp();
    });

    
  }

  handleChange (value) {
    this.setState({
        radioVal: value
    })
  }

  /**
 * javascript验证纳税人识别号格式
 * @param  taxId [纳税人识别号]
 * @return true格式正确，false格式错误
 */
checkTaxId(taxId) {
    var regArr = [/^[\da-z]{10,15}$/i, /^\d{6}[\da-z]{10,12}$/i, /^[a-z]\d{6}[\da-z]{9,11}$/i, /^[a-z]{2}\d{6}[\da-z]{8,10}$/i, /^\d{14}[\dx][\da-z]{4,5}$/i, /^\d{17}[\dx][\da-z]{1,2}$/i, /^[a-z]\d{14}[\dx][\da-z]{3,4}$/i, /^[a-z]\d{17}[\dx][\da-z]{0,1}$/i, /^[\d]{6}[\da-z]{13,14}$/i],
        i, j = regArr.length;
    for (var i = 0; i < j; i++) {
        if (regArr[i].test(taxId)) {
            return true;
        }
    }
    //纳税人识别号格式错误
    return false;
}
  async getFp() {
      let { data } = await $Req({
        type: "post",
        url: "/orderReceipt/getOrderReceiptByOrderId",
        data: { orderId: this.state.details.ordersId }
      });
      if (!data) return;
      console.log(data);
      this.setState({
        form: data,
        editFalse: true,
        createTime: data.createTime,
        radioVal: "" + data.receiptType
      })
  }
  async onSubmit (event,e) {
    const {
        userModel: { userInfo },
      } = this.props;

    for (const key in this.state.form) {
        let item = this.state.form[key];
        console.log(item);
        console.log(key);
        if (!item && item != 0) {
            Taro.showToast({
                title: "请填写所有的必填项",
                icon: "none"
            })
            return false;
        }
        
        switch(key) {
            case "phone":
                if(!(/^1[3456789]\d{9}$/.test(item))){ 
                    Taro.showToast({
                        title: "手机号有误",
                        icon: "none"
                    })
                    return false; 
                } 
                break;
            case "email":
                var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
                if(!(reg.test(item))){ 
                    Taro.showToast({
                        title: "邮箱格式错误",
                        icon: "none"
                    })
                    return false; 
                } 
                break;
            case "receiptBrandNum":
                if(isNaN(item)){ 
                    Taro.showToast({
                        title: "银行账号有误",
                        icon: "none"
                    })
                    return false; 
                } 
                break;
            case "receiptTaxpayerNum":
                if(!this.checkTaxId(item)){ 
                    Taro.showToast({
                        title: "纳税人识别号有误",
                        icon: "none"
                    })
                    return false; 
                } 
                break;
        }
    }

    this.state.form.receiptPrice = this.state.details.finalAmount
    this.state.form.orderId = this.state.details.ordersId
    this.state.form.orderType = 0
    this.state.form.receiptType = this.state.radioVal
    this.state.form.userId = userInfo.userId

    let { data } = await $Req({
        type: "post",
        url: "/orderReceipt/addOrderReceipt",
        data: this.state.form
      });
      if (!data) return;
    
      Taro.showToast({
          title: `申请成功！稍后发送至${this.state.form.email}邮箱！`,
          icon: "none"
      })

      setTimeout(() => {
        Taro.navigateBack(-1);
      }, 2000)
  }

  render() {
    return (
      <View className="page-user-relate1" style="padding: 10px">
        {/* 开发票输入框 */}
        <View>
          <AtForm
            onSubmit={this.onSubmit.bind(this)}
          >
            <AtInput
              disabled={this.state.editFalse}
              name="receiptCompany"
              title="公司名称"
              type="text"
              placeholder="开票公司名称"
              required
              value={this.state.form.receiptCompany}
              onChange={ value => {
                  this.state.form.receiptCompany = value;
                  this.setState({
                      form: this.state.form
                  })
              }}
            />
            <AtInput
              disabled={this.state.editFalse}
              name="receiptTaxpayerNum"
              title="纳税识别号"
              type="text"
              placeholder="纳税人识别号"
              required
              value={this.state.form.receiptTaxpayerNum}
              onChange={ value => {
                  this.state.form.receiptTaxpayerNum = value;
                  this.setState({
                      form: this.state.form
                  })
              }}
            />
            <AtInput
            disabled={this.state.editFalse}
              name="receiptBrandName"
              title="开户行名称"
              type="text"
              placeholder="开户行名称"
              required
              value={this.state.form.receiptBrandName}
              onChange={ value => {
                this.state.form.receiptBrandName = value;
                this.setState({
                    form: this.state.form
                })
            }}
            />
            <AtInput
            disabled={this.state.editFalse}
              name="receiptBrandNum"
              title="银行账号"
              type="text"
              placeholder="银行账号"
              required
              value={this.state.form.receiptBrandNum}
              onChange={ value => {
                this.state.form.receiptBrandNum = value;
                this.setState({
                    form: this.state.form
                })
            }}
            />
            <AtInput
            disabled={this.state.editFalse}
              name="receiptUserName"
              title="姓名"
              type="text"
              placeholder="姓名"
              required
              value={this.state.form.receiptUserName}
              onChange={ value => {
                this.state.form.receiptUserName = value;
                this.setState({
                    form: this.state.form
                })
            }}
            />
            <AtInput
            disabled={this.state.editFalse}
              name="phone"
              title="电话"
              type="text"
              placeholder="电话"
              required
              value={this.state.form.phone}
              onChange={ value => {
                this.state.form.phone = value;
                this.setState({
                    form: this.state.form
                })
            }}
            />
            <AtInput
            disabled={this.state.editFalse}
              name="email"
              title="邮箱"
              type="text"
              placeholder="邮箱"
              required
              value={this.state.form.email}
              onChange={ value => {
                this.state.form.email = value;
                this.setState({
                    form: this.state.form
                })
            }}
            />
            <AtInput
            disabled={this.state.editFalse}
              name="address"
              title="地址"
              type="text"
              placeholder="地址"
              required
              value={this.state.form.address}
              onChange={ value => {
                this.state.form.address = value;
                this.setState({
                    form: this.state.form
                })
            }}
            />
            <View style={{color: this.state.editFalse ? '#ccc': '#666', margin: "10px", fontSize: "14px"}}>
                请选择发票类型：
            </View>
            <AtRadio
                options={[
                { label: '增值税专用发票', value: '1', disabled: this.state.editFalse },
                { label: '增值税普通发票', value: '2', disabled: this.state.editFalse }
                ]}
                value={this.state.radioVal}
                onClick={this.handleChange.bind(this)}
            />
            {
                !this.state.editFalse ?
                    <View style="margin: 30px 0">
                        <AtButton formType="submit">提交</AtButton>
                    </View>
                :
                <AtInput
                disabled={this.state.createTime}
                title="申请时间"
                type="text"
                placeholder="申请时间"
                value={this.state.createTime}
                />
            }
          </AtForm>
        </View>
      </View>
    );
  }
}
